package com.lanou3g.code0418.dirty;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Created by dllo on 18/4/17.
 */
public class Utils {
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    //默认非公平锁,效率是最高的,主要看谁能抢,谁就先来
    //但是如果一直在读操作,写操作,进不去,系统对其进行分配线程,让其进行写操作
    //公平锁,谁先在等,然后开锁后,让谁来
    //读写锁,在写的时候,要写和要读,都不可以,等其写完,才能运行写与读,之后就看谁能
    //抢;在读的时候,要写和要读,读可以进来读,但是写,要在外面等,等到读完再写
    public void updatePerson(Person person, String name, int age) {
        lock.writeLock().lock();
        person.setName(name);
        //让线程沉睡1s,为了让脏读效果更容易出现
        try

        {
            Thread.sleep(1000);
        } catch (
                InterruptedException e)

        {
            e.printStackTrace();
        }
        person.setAge(age);
        lock.writeLock().unlock();
    }

    public void showPerson(Person person) {
        lock.readLock().lock();
        System.out.println("姓名:" + person.getName());
        System.out.println("年龄:" + person.getAge());
        lock.readLock().unlock();
    }
}
